package guru.util;

import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

public class Params{
    static Logger logger = Logger.getLogger(Params.class);

    
    
	public Properties props=new Properties();


	public Params(String initFilePath) throws Exception{
		props.load(new FileInputStream(initFilePath));
	}

	/**
	 * @param mandatoryParams Secuencia de claves obligatorias separada por un ";"
	 */
	public Params(String initFilePath,String mandatoryParams) throws Exception{
		StringBuffer out=new StringBuffer();
		StringTokenizer st;
		String param;
		Enumeration e;
		boolean found;
		String tmpstr;

		props.load(new FileInputStream(initFilePath));

		if(mandatoryParams!=null){
			st=new StringTokenizer(mandatoryParams,";");

			for(;st.hasMoreTokens();){
				param=st.nextToken();
				found=false;
				for(e=props.propertyNames();e.hasMoreElements();){
					tmpstr=(String)e.nextElement();
					if(tmpstr.equalsIgnoreCase(param)){
						found=true;
						break;
					}
				}
				if(!found){
					out.append(param+";");
				}
			}
			if(out.length()!=0){
				throw new Exception("Initialization file lacks of the following mandatory parameters: "+out);
			}
		}

	}

	public String getValue(String key,String def){
		String tmpstr;

		if((tmpstr=props.getProperty(key))!=null){
			return(tmpstr);
		}
		else{
			logger.warn("'"+key+"' value not specified. Using default value: "+def);
			return(def);
		}
	}

	public String getValue(String key){
		String tmpstr;

		if((tmpstr=props.getProperty(key))!=null){
			return(tmpstr);
		}
		else{
			tmpstr="INTERNAL ERROR: '"+key+"' value not specified while spected MANDATORY.";
			logger.error(tmpstr);
			throw new Error(tmpstr);
		}
	}

	public int intValue(String key, int def){
		String tmpstr;
		int out;

		if((tmpstr=props.getProperty(key))!=null){
			try{
				out=new Integer(tmpstr).intValue();
			}
			catch(Exception e){
				logger.error("'"+key+"' value is not an Integer. Using default value: "+def);
				return(def);
			}
		}
		else{
			logger.warn("'"+key+"' value not specified. Using default value: "+def);
			return(def);
		}
		return(out);
	}
}



